package com.cskaoyan.service.goods;

import com.cskaoyan.bean.goods.*;
import com.cskaoyan.bean.market.*;
import com.cskaoyan.bean.promotion.GrouponExample;
import com.cskaoyan.bean.promotion.GrouponRules;
import com.cskaoyan.bean.promotion.GrouponRulesExample;
import com.cskaoyan.bean.user.CollectExample;
import com.cskaoyan.bo.goods.GoodsCreateAndUpdateBo;
import com.cskaoyan.bo.goods.GoodsPageAndSortBo;
import com.cskaoyan.mapper.*;
import com.cskaoyan.service.wxfree.WxFootprintService;
import com.cskaoyan.vo.goods.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;

/**
 * description:goods模块的service层的代码
 * author:houzhitao@139.com
 */
@Service
public class GoodsServiceImpl implements GoodsService {
    @Autowired
    GoodsMapper goodsMapper;
    @Autowired
    GoodsProductMapper goodsProductMapper;
    @Autowired
    GoodsAttributeMapper goodsAttributeMapper;
    @Autowired
    GoodsSpecificationMapper goodsSpecificationMapper;
    @Autowired
    CategoryMapper categoryMapper;
    @Autowired
    BrandMapper brandMapper;
    @Autowired
    CollectMapper collectMapper;
    @Autowired
    CommentMapper commentMapper;
    @Autowired
    GrouponRulesMapper grouponRulesMapper;
    @Autowired
    IssueMapper issueMapper;
    @Autowired
    WxFootprintService wxFootprintService;

    @Override
    public GoodsListVo goodsList(GoodsPageAndSortBo pageAndSortBo) {
        PageHelper.startPage(pageAndSortBo.getPage(), pageAndSortBo.getLimit());//mybatis构建分页sql语句

        //goodslist的查询
        GoodsExample goodsExample = new GoodsExample();
        goodsExample.setOrderByClause(pageAndSortBo.getSort() + " " + pageAndSortBo.getOrder()); //sql拼接
        GoodsExample.Criteria criteria = goodsExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        if (pageAndSortBo.getGoodsSn() != null && !"".equals(pageAndSortBo.getGoodsSn())) {
            criteria.andGoodsSnEqualTo(pageAndSortBo.getGoodsSn());
        }
        if (pageAndSortBo.getName() != null && !"".equals(pageAndSortBo.getName())) {
            criteria.andNameLike("%" + pageAndSortBo.getName() + "%");
        }

        List<Goods> goods = goodsMapper.selectByExample(goodsExample);

        //满足条件的所有数据量total
        PageInfo<Goods> goodsPageInfo = new PageInfo<>(goods);//查询结果所放之处
        long total = goodsPageInfo.getTotal();//总的数据量

        GoodsListVo goodsListVo = new GoodsListVo();
        goodsListVo.setTotal(total);
        goodsListVo.setItems(goods);

        return goodsListVo;
    }

    @Override
    @Transactional
    public Integer goodsCreate(GoodsCreateAndUpdateBo goodsCreateBo) {
        Goods goods = goodsCreateBo.getGoods();
        //插入goods的信息
        int goodsId = 0;
        if (goods != null && !"".equals(goods)) {
            goodsId = goodsMapper.insertSelective(goods);
        }

        //给要插入的products赋值goods_id,并批量插入goods_product
        List<GoodsProduct> products = goodsCreateBo.getProducts();
        for (GoodsProduct product : products) {
            product.setGoodsId(goodsId);
        }
        int productsNum = 0;
        if (products != null && products.size() > 0) {
            productsNum = goodsProductMapper.insertBatch(products);
        }

        // attribute赋值goods_id,并批量插入goods_attribute
        List<GoodsAttribute> attributes = goodsCreateBo.getAttributes();
        for (GoodsAttribute attribute : attributes) {
            attribute.setGoodsId(goodsId);
        }
        int attributeNum = 0;
        if (attributes != null && attributes.size() != 0) {
            attributeNum = goodsAttributeMapper.insertBatch(attributes);
        }

        // specification赋值goods_id,并批量插入goods_specification
        List<GoodsSpecification> specifications = goodsCreateBo.getSpecifications();
        for (GoodsSpecification specification : specifications) {
            specification.setGoodsId(goodsId);
        }
        int specificationsNum = 0;
        if (specifications != null && specifications.size() != 0) {
            specificationsNum = goodsSpecificationMapper.insertBatch(specifications);
        }
        return goodsId;
    }

    @Override
    public Integer goodsDelete(Goods goods) {
        Goods goodsDelete = new Goods();
        goodsDelete.setId(goods.getId());
        goodsDelete.setDeleted(true);
        //删除为浅删除，即将deleted改为true
        int effectNum = goodsMapper.updateByPrimaryKeySelective(goodsDelete);
        return effectNum;
    }

    @Transactional
    @Override
    public Integer goodsUpdate(GoodsCreateAndUpdateBo goodsUpdateBo) {
        //根据id修改goods的信息
        Goods goods = goodsUpdateBo.getGoods();
        int goodsUpdateNum = goodsMapper.updateByPrimaryKeySelective(goods);

        //根据id批量修改specification
        int specificationsUpDateNum;
        List<GoodsSpecification> specifications = goodsUpdateBo.getSpecifications();
        for (GoodsSpecification specification : specifications) {
            specificationsUpDateNum = goodsSpecificationMapper.updateByPrimaryKeySelective(specification);
        }
        //根据id批量修改product
        int productUpDateNum;
        List<GoodsProduct> products = goodsUpdateBo.getProducts();
        for (GoodsProduct product : products) {
            productUpDateNum = goodsProductMapper.updateByPrimaryKeySelective(product);
        }
        //根据id批量修改attribute
        int attributeUpDateNum;
        List<GoodsAttribute> attributes = goodsUpdateBo.getAttributes();
        for (GoodsAttribute attribute : attributes) {
            attributeUpDateNum = goodsAttributeMapper.updateByPrimaryKeySelective(attribute);
        }

        return goodsUpdateNum;
    }

    @Override
    public GoodsDetailVo goodsDetail(Integer id) {
        if (id == null || "".equals(id)) {
            return null;
        }

        GoodsDetailVo goodsDetailVo = new GoodsDetailVo();
        //根据id查询goods信息
        GoodsExample goodsExample = new GoodsExample();
        GoodsExample.Criteria criteria = goodsExample.createCriteria();
        criteria.andIdEqualTo(id).andDeletedEqualTo(false);
        Goods goods = goodsMapper.selectByExample(goodsExample).get(0);

        //根据goodsId查询attributeList信息
        GoodsAttributeExample goodsAttributeExample = new GoodsAttributeExample();
        GoodsAttributeExample.Criteria criteria1 = goodsAttributeExample.createCriteria();
        criteria1.andGoodsIdEqualTo(id).andDeletedEqualTo(false);
        List<GoodsAttribute> goodsAttributes = goodsAttributeMapper.selectByExample(goodsAttributeExample);

        //根据goodsId查询specification信息
        GoodsSpecificationExample goodsSpecificationExample = new GoodsSpecificationExample();
        GoodsSpecificationExample.Criteria criteria2 = goodsSpecificationExample.createCriteria();
        criteria2.andGoodsIdEqualTo(id).andDeletedEqualTo(false);
        List<GoodsSpecification> goodsSpecifications = goodsSpecificationMapper.selectByExample(goodsSpecificationExample);

        //根据goodsId查询product信息
        GoodsProductExample goodsProductExample = new GoodsProductExample();
        GoodsProductExample.Criteria criteria3 = goodsProductExample.createCriteria();
        criteria3.andGoodsIdEqualTo(id).andDeletedEqualTo(false);
        List<GoodsProduct> goodsProducts = goodsProductMapper.selectByExample(goodsProductExample);

        //根据查询的goods信息中的categoryId成员变量，查询id，和pid,输出为[pid,id]
        List<Integer> categoryIds = new ArrayList<>();
        if (goods != null) {
            Integer categoryId = goods.getCategoryId();
            Category category = categoryMapper.selectByPrimaryKey(categoryId);
            categoryIds.add(category.getPid());
            categoryIds.add(categoryId);
        }
        //将上边的查询结果作为参数赋值给GoodsDetailVo的成员变量
        goodsDetailVo.setGoods(goods);
        goodsDetailVo.setAttributes(goodsAttributes);
        goodsDetailVo.setCategoryIds(categoryIds);
        goodsDetailVo.setProducts(goodsProducts);
        goodsDetailVo.setSpecifications(goodsSpecifications);


        if (goods == null) {
            return null;
        }
        return goodsDetailVo;
    }

    @Override
    public GoodsCatAndBrandVo queryCatAndBrand() {
        GoodsCatAndBrandVo catAndBrandVo = new GoodsCatAndBrandVo();
        //查询所有的brand，封装到list中
        List<BrandVo> brandVoList = brandMapper.selectIdAndName();

        //查询所有的category,注意有子嵌套
        List<CategoryGoodsVo> categoryVoList = categoryMapper.selectIdAndName(0);
        List<CategoryChildrenVo> children;
        for (CategoryGoodsVo categoryVo : categoryVoList) {
            children = categoryMapper.selectIdAndNameByPid(categoryVo.getValue());
            categoryVo.setChildren(children);
        }
        //将上边两个list赋值给要返回的对象
        catAndBrandVo.setBrandList(brandVoList);
        catAndBrandVo.setCategoryList(categoryVoList);
        return catAndBrandVo;
    }

    @Override
    public WxGoodsCountVo countGoods() {
        WxGoodsCountVo countVo = new WxGoodsCountVo();
        //统计统计商品总数量
        GoodsExample goodsExample = new GoodsExample();
        long count = goodsMapper.countByExample(goodsExample);
        countVo.setGoodsCount(count);
        return countVo;
    }

    @Override
    public WxGoodsListVo wxQueryGoodsList(Integer categoryId, Integer page, Integer size) {
        //分页
        PageHelper.startPage(page, size);

        //根据categoryId查询goodsList
        List<WxGoodsListSonVo> goodsListSonVos = goodsMapper.selectByCategoryId(categoryId);

        //查询goodsList中商品总数量
        PageInfo<WxGoodsListSonVo> wxGoodsListSonVoPageInfo = new PageInfo<>(goodsListSonVos);
        long total = wxGoodsListSonVoPageInfo.getTotal();

        //根据categoryId作为pid查询categoryList
        CategoryExample categoryExample = new CategoryExample();
        CategoryExample.Criteria criteria = categoryExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        if (categoryId != null && !"".equals(categoryId)) {
            criteria.andPidEqualTo(categoryId);
        }
        List<Category> categories = categoryMapper.selectByExample(categoryExample);

        //将上边查询的三个结果赋值给要返回结果的bean中
        WxGoodsListVo wxGoodsListVo = new WxGoodsListVo();
        wxGoodsListVo.setCount(total);
        wxGoodsListVo.setFilterCategoryList(categories);
        wxGoodsListVo.setGoodsList(goodsListSonVos);

        return wxGoodsListVo;
    }

    @Override
    public WxGoodsCategoryVo wxQueryGoodsCategory(Integer id) {
        if (id == null || "".equals(id)) {
            return null;
        }
        //根据id查询
        CategoryExample categoryExample1 = new CategoryExample();
        categoryExample1.createCriteria().andDeletedEqualTo(false).andIdEqualTo(id);
        List<Category> categories1 = categoryMapper.selectByExample(categoryExample1);
        Category currentCategory = null;
        if (categories1.size() != 0) {
            currentCategory = categories1.get(0);
        } else {
            return null;
        }

        //根据currentCategory中的pid作为id查询
        CategoryExample categoryExample2 = new CategoryExample();
        CategoryExample.Criteria criteria = categoryExample2.createCriteria().andDeletedEqualTo(false);
        if (currentCategory.getPid() != null && !"".equals(currentCategory.getPid())) {
            criteria.andIdEqualTo(currentCategory.getPid());
        }
        List<Category> categories2 = categoryMapper.selectByExample(categoryExample2);
        Category parentCategory = null;
        if (categories2.size() != 0) {
            parentCategory = categories2.get(0);
        }

        //根据currentCategory中的pid作为pid查询
        CategoryExample categoryExample3 = new CategoryExample();
        CategoryExample.Criteria criteria1 = categoryExample3.createCriteria().andDeletedEqualTo(false);
        if (currentCategory.getPid() != null && !"".equals(currentCategory.getPid())) {
            criteria1.andPidEqualTo(currentCategory.getPid());
        }
        List<Category> brotherCategories = categoryMapper.selectByExample(categoryExample3);

        //将上边查询结果赋值给要返回的值的成员变量
        WxGoodsCategoryVo categoryVo = new WxGoodsCategoryVo();
        categoryVo.setCurrentCategory(currentCategory);
        categoryVo.setParentCategory(parentCategory);
        categoryVo.setBrotherCategory(brotherCategories);

        return categoryVo;
    }

    @Override
    public WxGoodsDetailVo wxGoodsDetail(Integer id) {
        if (id == null || "".equals(id)) {
            return null;
        }

        //根据商品id作为value_id查询collect中数量
        CollectExample collectExample = new CollectExample();
        collectExample.createCriteria().andValueIdEqualTo(id).andDeletedEqualTo(false);
        long userHasCollect = collectMapper.countByExample(collectExample);

        //根据商品id作为value_id查询comment中数量和list详情
        CommentExample commentExample = new CommentExample();
        commentExample.createCriteria().andValueIdEqualTo(id).andDeletedEqualTo(false);
        List<Comment> comments = commentMapper.selectByExample(commentExample);
        WxGoodsDetailSonCommentVo wxGoodsDetailSonCommentVo = new WxGoodsDetailSonCommentVo();
        wxGoodsDetailSonCommentVo.setData(comments);
        wxGoodsDetailSonCommentVo.setCount((long) comments.size());

        //根据id查询商品详情,（查询结果将share_url赋值为null）
        GoodsExample goodsExample = new GoodsExample();
        goodsExample.createCriteria().andDeletedEqualTo(false).andIdEqualTo(id);
        List<Goods> goodsList = goodsMapper.selectByExample(goodsExample);
        Goods goods = new Goods();
        if (goodsList.size() > 0) {
            goods = goodsList.get(0);
        }
        goods.setShareUrl(null);

        //根据查出的商品info的brandId作为id在brand中查询brand详情
        BrandExample brandExample = new BrandExample();
        if (goods.getBrandId() != null) {
            brandExample.createCriteria().andDeletedEqualTo(false).andIdEqualTo(goods.getBrandId());
        }
        List<Brand> brands = brandMapper.selectByExample(brandExample);
        Brand brand = null;
        if (brands.size() != 0) {
            brands.get(0);
        }

        //首先根据商品id作为goods_id在specification表中查询去重specification属性
        List<String> specifications = goodsSpecificationMapper.selectSpecificationByGoodId(id);
        //遍历specification属性，并根据goodsid和specification两个条件查询并封装于List<GoodsSpecification> 中
        ArrayList<WxGoodsDetailSonSpecificVo> specificationList = new ArrayList<>();
        for (String specification : specifications) {
            WxGoodsDetailSonSpecificVo wxGoodsDetailSonSpecificVo = new WxGoodsDetailSonSpecificVo();
            //给name属性赋值
            wxGoodsDetailSonSpecificVo.setName(specification);
            //查询List<GoodsSpecification> ，并给该属性赋值
            GoodsSpecificationExample goodsSpecificationExample = new GoodsSpecificationExample();
            goodsSpecificationExample.createCriteria().andDeletedEqualTo(false).andGoodsIdEqualTo(id).andSpecificationEqualTo(specification);
            List<GoodsSpecification> goodsSpecifications = goodsSpecificationMapper.selectByExample(goodsSpecificationExample);
            wxGoodsDetailSonSpecificVo.setValueList(goodsSpecifications);
            //将wxGoodsDetailSonSpecificVo实例加入specificationList中
            specificationList.add(wxGoodsDetailSonSpecificVo);
        }

        // 根据商品id作为goods_id查询groupon_rules详情
        GrouponRulesExample grouponRulesExample = new GrouponRulesExample();
        grouponRulesExample.createCriteria().andDeletedEqualTo(false).andGoodsIdEqualTo(id);
        List<GrouponRules> grouponRules = grouponRulesMapper.selectByExample(grouponRulesExample);

        //在issue表中查出全部信息
        IssueExample issueExample = new IssueExample();
        issueExample.createCriteria().andDeletedEqualTo(false);
        List<Issue> issues = issueMapper.selectByExample(issueExample);

        //根据商品id作为goods_id在attribute中查询
        GoodsAttributeExample goodsAttributeExample = new GoodsAttributeExample();
        goodsAttributeExample.createCriteria().andDeletedEqualTo(false).andGoodsIdEqualTo(id);
        List<GoodsAttribute> goodsAttributes = goodsAttributeMapper.selectByExample(goodsAttributeExample);

        //根据商品id作为goods_id在product中查询详情
        GoodsProductExample goodsProductExample = new GoodsProductExample();
        goodsProductExample.createCriteria().andGoodsIdEqualTo(id).andDeletedEqualTo(false);
        List<GoodsProduct> goodsProducts = goodsProductMapper.selectByExample(goodsProductExample);

        //将上述查询结果赋值给要返回的参数的成员变量
        WxGoodsDetailVo wxGoodsDetailVo = new WxGoodsDetailVo();
        wxGoodsDetailVo.setUserHasCollect(userHasCollect);
        wxGoodsDetailVo.setComment(wxGoodsDetailSonCommentVo);
        wxGoodsDetailVo.setBrand(brand);
        wxGoodsDetailVo.setInfo(goods);
        wxGoodsDetailVo.setSpecificationList(specificationList);
        wxGoodsDetailVo.setGroupon(grouponRules);
        wxGoodsDetailVo.setIssue(issues);
        wxGoodsDetailVo.setAttribute(goodsAttributes);
        wxGoodsDetailVo.setProductList(goodsProducts);
// 插入足迹
        wxFootprintService.insertFootprint(id);
        return wxGoodsDetailVo;
    }

    @Override
    public WxGoodsRelatedVo goodsRelated(Integer id) {
        if (id == null || "".equals(id)) {
            return null;
        }
        //根据keywords 或 name 模糊查询，并且根据是热门 查询商品
        //根据id查询商品详情,
        GoodsExample goodsExample = new GoodsExample();
        goodsExample.createCriteria().andDeletedEqualTo(false).andIdEqualTo(id);
        List<Goods> goodsListTemp = goodsMapper.selectByExample(goodsExample);
        if (goodsListTemp.size() == 0) {
            return null;
        }
        String keywords = goodsListTemp.get(0).getKeywords();

        //根据根据关键字模糊查询relatedList
        List<WxGoodsListSonVo> goodsList = goodsMapper.selectRelatedByKeyword(keywords, id);
        WxGoodsRelatedVo wxGoodsRelatedVo = new WxGoodsRelatedVo();
        wxGoodsRelatedVo.setGoodsList(goodsList);
        return wxGoodsRelatedVo;
    }


}
